﻿using PmSadis.Repositories.Abstract;
using PmSadis.Models;
using System.Linq;
using PmSadis.Dal;
using System;
using System.Data.Entity;

namespace PmSadis.Repositories
{
    /// <summary>
    /// Хранилище механизмов справочных работ
    /// </summary>
    public class WorkMechanismRepository : IListRepository<WorkMechanism>
    {
        private ModelsContext _context = new ModelsContext();

        /// <summary>
        /// Полный список механизмов
        /// </summary>
        public IQueryable<WorkMechanism> All
        {
            get
            {
                return _context.WorkMechanisms;
            }
        }

        /// <summary>
        /// Удалить механизм
        /// </summary>
        /// <param name="id">Идентификатор механизма</param>
        public void Delete(object id)
        {
            var workMechanismId = (int)id;
            var workMechanism = _context.WorkMechanisms.FirstOrDefault(x => x.WorkMechanismId == workMechanismId);
            if (workMechanism == null) return;

            _context.WorkMechanisms.Remove(workMechanism);
            _context.SaveChanges();
        }

        /// <summary>
        /// Создать или редактировать механизм
        /// </summary>
        /// <param name="workMechanism">Mеханизм</param>
        public object Edit(WorkMechanism workMechanism)
        {
            var dateNow = DateTime.Now;
            if (workMechanism.WorkMechanismId == 0)
            {
                workMechanism.DateCreate = dateNow;
                workMechanism.DateUpdate = dateNow;
                _context.Entry(workMechanism).State = EntityState.Added;
            }
            else
            {
                workMechanism.DateUpdate = dateNow;
                _context.Entry(workMechanism).State = EntityState.Modified;
            }

            _context.SaveChanges();

            return workMechanism.WorkMechanismId;
        }
    }
}
